from rest_framework.views import APIView
from rest_framework.response import Response
from .models import User

from rest_framework.generics import CreateAPIView
from .serializers import UserCreateSerializer
from .serializers import UserDetailSerializer
from rest_framework.generics import RetrieveAPIView
from rest_framework.permissions import IsAuthenticated

from rest_framework.generics import UpdateAPIView
from .serializers import EmailSerializer
from rest_framework import status


# 用户名
class UserNameCountView(APIView):
    def get(self, request, username):
        # 统计用户名是否存在
        count = User.objects.filter(username=username).count()
        return Response({
            'username': username,
            'count': count,
        })


# 手机号
class MobileCountView(APIView):
    def get(self, request, mobile):
        # 统计手机号是否存在
        count = User.objects.filter(mobile=mobile).count()

        return Response({
            'mobile': mobile,
            'count': count
        })


# 序列化器
class UserView(CreateAPIView):
    # 完成用户注册
    serializer_class = UserCreateSerializer


class UserDetailView(RetrieveAPIView):
    """用户详情"""
    serializer_class = UserDetailSerializer
    # 要求登录后才能访问，指定权限认证
    permission_classes = [IsAuthenticated]

    # 当前不需要根据pk查询对象，而是获取登录的用户对象
    def get_object(self):
        # 当jwt当成验证登录后，会将对象保存到request对象
        return self.request.user


class EmailView(UpdateAPIView):
    # 保存用户邮箱
    permission_classes = [IsAuthenticated]
    serializer_class = EmailSerializer

    def get_object(self, *args, **kwargs):
        return self.request.user


class VerifyEmailView(APIView):
    """
    邮箱验证
    """
    def get(self, request):
        # 获取token
        token = request.query_params.get('token')
        if not token:
            return Response({'message': '缺少token'}, status=status.HTTP_400_BAD_REQUEST)

        # 验证token
        user = User.check_verify_email_token(token)
        if user is None:
            return Response({'message': '链接信息无效'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            user.email_active = True
            user.save()
            return Response({'message': 'OK'})
